/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.hanfu.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.common.util.OssIdClearUtils;
import top.continew.admin.hanfu.core.oss.OSS;
import top.continew.admin.hanfu.domain.Hanfu;
import top.continew.admin.hanfu.domain.OssFile;
import top.continew.admin.hanfu.domain.bo.HanfuBo;
import top.continew.admin.hanfu.domain.dto.HanfuDto;
import top.continew.admin.hanfu.domain.vo.HanfuVo;
import top.continew.admin.hanfu.domain.vo.wx.HanfuWxDeVo;
import top.continew.admin.hanfu.domain.vo.wx.HanfuWxVo;
import top.continew.admin.hanfu.mapper.HanfuMapper;
import top.continew.admin.hanfu.service.IHanfuService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bbm
 * @since 2025-03-20
 */
@Service
@RequiredArgsConstructor
public class HanfuServiceImpl extends ServiceImpl<HanfuMapper, Hanfu> implements IHanfuService {

    private final HanfuMapper hanfuMapper;

    private final OssFileServiceImpl ossFileService;

    private final OSS oss;

    @Override
    public Page<HanfuVo> getHanfuListByTypeId(Integer typeId, Integer pageNum, Integer pageSize) {

        HanfuBo hanfuBo = new HanfuBo();
        hanfuBo.setHanfuTypeId(typeId);

        return null;
    }

    @Override
    public Page<HanfuWxVo> getHanfuWxListByTypeId(String typeName,
                                                  Integer typeId,
                                                  String queryName,
                                                  Integer pageNum,
                                                  Integer pageSize) {

        HanfuBo hanfuBo = new HanfuBo();
        hanfuBo.setHanfuTypeId(typeId == 0 ? null : typeId);
        hanfuBo.setHanfuTypeName(typeName.isEmpty() ? null : typeName);
        hanfuBo.setHanfuName(queryName.isEmpty() ? null : queryName);

        return hanfuMapper.getHanfuWxListByTypeId(new Page<>(pageNum, pageSize), hanfuBo);
    }

    /**
     * 获取汉服列表
     * 
     * @param typeName
     * @param queryName
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<HanfuVo> getHanfuListByCondition(String typeName,
                                                 String queryName,
                                                 Integer status,
                                                 Integer pageNum,
                                                 Integer pageSize) {

        HanfuBo hanfuBo = new HanfuBo();

        if (typeName == null || typeName.equals("")) {
            typeName = null;
        }

        if (queryName == null || queryName.equals("")) {
            queryName = null;
        }

        hanfuBo.setHanfuTypeName(typeName);
        hanfuBo.setHanfuName(queryName);
        hanfuBo.setStatus(status);

        return hanfuMapper.getHanfuListByCondition(new Page<>(pageNum, pageSize), hanfuBo);
    }

    @Override
    public int addHanfu(HanfuBo hanfu) {

        Hanfu h = new Hanfu();

        MultipartFile[] array = hanfu.getFile().toArray(new MultipartFile[0]);
        List<OssFile> ossFiles = oss.saveFile("hanfuImg", hanfu.getUpdataBy(), array);

        if (ossFiles.isEmpty()) {
            return 0;
        }

        StringBuilder stringBuilder = new StringBuilder();
        ossFiles.forEach(item -> {
            stringBuilder.append(item.getOssId()).append(",");
        });

        stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());

        h.setHanfuName(hanfu.getHanfuName());
        h.setHanfuPrice(hanfu.getHanfuPrice());
        h.setHanfuTypeId(hanfu.getHanfuTypeId());
        h.setUpdataBy(hanfu.getUpdataBy());
        h.setDescription(hanfu.getDescription());
        h.setOssId(OssIdClearUtils.cleanFrontCover(stringBuilder.toString()));
        h.setUpdataTime(System.currentTimeMillis() + "");
        h.setStatus(hanfu.getStatus());

        boolean save = save(h);

        return save ? 1 : 0;
    }

    @Override
    public int updateHanfuImg(HanfuBo hanfuBo) {

        //先查询原有的文件
        Hanfu byId = getById(hanfuBo.getHanfuId());

        //旧文件组
        String[] ossId = byId.getOssId().split(",");

        //新文件组
        List<String> newOssId = Arrays.stream(hanfuBo.getOssId().split(",")).toList();

        List<String> collect = new ArrayList<>();

        //求两个数组之间的差集

        for (String oss : ossId) {
            boolean contains = newOssId.contains(oss);
            if (!contains) {
                collect.add(oss);
            }
        }

        //删除差集
        oss.deleteFiles(collect);

        List<MultipartFile> file = hanfuBo.getFile();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(hanfuBo.getOssId()).append(",");
        if (file != null && !file.isEmpty()) {

            //            调用oss保存方法
            List<OssFile> hanfuImg = oss.saveFile("hanfuImg", hanfuBo.getUpdataBy(), file
                .toArray(new MultipartFile[] {}));

            for (OssFile ossFile : hanfuImg) {
                stringBuilder.append(ossFile.getOssId()).append(",");
            }

            stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());

        }

        boolean update = lambdaUpdate().eq(Hanfu::getHanfuId, hanfuBo.getHanfuId())
            .set(!stringBuilder.toString().isEmpty(), Hanfu::getOssId, stringBuilder.toString())
            .set(Hanfu::getUpdataBy, hanfuBo.getUpdataBy())
            .set(Hanfu::getUpdataTime, System.currentTimeMillis())
            .update();

        return update ? 1 : 0;
    }

    @Override
    public int deleteHanfu(ArrayList<Integer> id) {

        return removeByIds(id) ? 1 : 0;
    }

    @Override
    public HanfuVo getHanfuById(Integer id) {
        return null;
    }

    @Override
    public HanfuWxDeVo getHanfuWxById(Integer id) {
        return hanfuMapper.getByHanfuIdWxDeVo(id);
    }

    @Override
    public int updateHanFu(HanfuDto hanfuDto) {

        boolean update = lambdaUpdate().set(!hanfuDto.getName().isEmpty(), Hanfu::getHanfuName, hanfuDto.getName())
            .set(hanfuDto.getPrice() != 0, Hanfu::getHanfuPrice, hanfuDto.getPrice())
            .set(Hanfu::getStatus, hanfuDto.getStatus())
            .set(!hanfuDto.getDescription().isEmpty(), Hanfu::getDescription, hanfuDto.getDescription())
            .set(hanfuDto.getTypeId() != 0, Hanfu::getHanfuTypeId, hanfuDto.getTypeId())
            .set(Hanfu::getUpdataBy, hanfuDto.getUpdataBy())
            .set(Hanfu::getUpdataTime, System.currentTimeMillis())
            .eq(Hanfu::getHanfuId, hanfuDto.getId())
            .update();

        return update ? 1 : 0;
    }

}
